<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '../plugins/axios'
import { config } from '../config'  // 导入基础URL配置
import { Plus } from '@element-plus/icons-vue'

const userInfo = ref({
  username: '',
  realname: '',
  phone: '',
  sex: '',
  email: '',
  head: '',
  birthday: '',
  hireDate: '',
  duty: '',
  emailNotifyEnabled: 0
})

// 性别选项
const sexOptions = [
  { value: '男', label: '男' },
  { value: '女', label: '女' }
]

// 添加默认头像路径
const defaultAvatar = '/default-avatar.png'

// 计算属性获取头像地址
const avatarSrc = computed(() => {
  if (userInfo.value.head) {
    return `${userInfo.value.head}`
  }
  return defaultAvatar
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const userId = localStorage.getItem('userId')
    const response = await axios.get(`/user/${userId}`)
    const data = response.data.data

    // 处理日期格式
    userInfo.value = {
      ...data,
      // 确保日期格式正确，如果日期为空则设为 null
      birthday: data.birthday ? formatDate(data.birthday) : null,
      hireDate: data.hireDate ? formatDate(data.hireDate) : null,
      emailNotifyEnabled: typeof data.emailNotifyEnabled === 'number' ? data.emailNotifyEnabled : 0
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return null
  
  // 处理不同的日期格式
  let date
  if (dateString.includes('T')) {
    // 处理 ISO 格式的日期
    date = new Date(dateString)
  } else if (dateString.includes('/')) {
    // 处理 yyyy/MM/dd 格式
    date = new Date(dateString.replace(/\//g, '-'))
  } else {
    // 处理 yyyy-MM-dd 格式或其他格式
    date = new Date(dateString)
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) return null

  // 格式化为 YYYY-MM-DD
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 添加上传前的验证函数
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 修改头像上传成功的处理函数
const handleAvatarSuccess = (response) => {
  if (response.code === 1) {
    // 保存返回的相对路径
    userInfo.value.head = response.data.filePath
    // 立即保存到后端
    handleSave()
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg || '头像上传失败')
  }
}

// 添加上传失败的处理函数
const handleAvatarError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 保存用户信息
const handleSave = async () => {
  try {
    const response = await axios.post('/user/update', userInfo.value)
    if (response.data.code === 1) {
      ElMessage.success('保存成功')
      // 更新本地存储的用户名
      localStorage.setItem('realname', userInfo.value.realname)
      const latestUsername = userInfo.value.username || userInfo.value.realname || ''
      const latestEmail = userInfo.value.email || ''
      if (latestUsername) {
        localStorage.setItem('username', latestUsername)
      } else {
        localStorage.removeItem('username')
      }
      if (latestEmail) {
        localStorage.setItem('userEmail', latestEmail)
      } else {
        localStorage.removeItem('userEmail')
      }
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('user-info-updated'))
      }
    } else {
      ElMessage.error(response.data.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 添加修改密码相关的响应式变量
const pwdDialogVisible = ref(false)
const pwdForm = ref({
  newPassword: '',
  confirmPassword: ''
})

// 修改密码验证规则
const pwdRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    { 
      // 修改密码规则：至少6位，允许字母、数字和特殊字符
      pattern: /^[A-Za-z0-9!@#$%^&*()_+\-=\[\]{};:'",.<>/?]{6,}$/,
      message: '密码长度不少于6位，允许字母、数字和特殊字符',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const pwdFormRef = ref(null)

// 处理密码修改
const handleUpdatePassword = async () => {
  if (!pwdFormRef.value) return
  
  await pwdFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.put('/user/pwd/update', {
          id: localStorage.getItem('userId'),
          pwd: pwdForm.value.newPassword
        })
        
        if (response.data.code === 1) {
          ElMessage.success('密码修改成功')
          pwdDialogVisible.value = false
          // 清空表单
          pwdForm.value.newPassword = ''
          pwdForm.value.confirmPassword = ''
        } else {
          ElMessage.error(response.data.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error('密码修改失败')
      }
    }
  })
}

// 关闭对话框时重置表单
const handleCloseDialog = () => {
  pwdFormRef.value?.resetFields()
  pwdForm.value.newPassword = ''
  pwdForm.value.confirmPassword = ''
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="personal-page">
    <div class="page-header">
      <h2>个人信息</h2>
    </div>

    <el-form 
      :model="userInfo" 
      label-width="100px"
      class="user-form"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :action="`${config.baseURL}/upload`"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          name="file"
        >
          <img v-if="avatarSrc" :src="avatarSrc" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="用户名">
        <el-input v-model="userInfo.username" disabled />
      </el-form-item>

      <el-form-item label="真实姓名">
        <el-input v-model="userInfo.realname" />
      </el-form-item>

      <el-form-item label="手机号码">
        <div class="phone-wrapper">
          <el-input v-model="userInfo.phone" />
          <el-button type="primary" @click="pwdDialogVisible = true">
            修改密码
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="userInfo.sex">
          <el-option
            v-for="option in sexOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="邮箱">
        <el-input v-model="userInfo.email" />
      </el-form-item>

      <el-form-item label="邮件提醒">
        <el-switch
          v-model="userInfo.emailNotifyEnabled"
          :active-value="1"
          :inactive-value="0"
          active-text="开启"
          inactive-text="关闭"
        />
      </el-form-item>

      <el-form-item label="生日">
        <el-date-picker
          v-model="userInfo.birthday"
          type="date"
          placeholder="选择生日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :clearable="true"
        />
      </el-form-item>

      <el-form-item label="入职日期">
        <el-date-picker
          v-model="userInfo.hireDate"
          type="date"
          placeholder="选择入职日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          disabled
          :clearable="false"
        />
      </el-form-item>

      <el-form-item label="职责">
        <el-input v-model="userInfo.duty" disabled />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>

    <!-- 添加修改密码对话框 -->
    <el-dialog
      v-model="pwdDialogVisible"
      title="修改密码"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="pwdFormRef"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="pwdForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
          <div class="password-tips">
            密码长度不少于6位，允许字母、数字和特殊字符
          </div>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="pwdForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="pwdDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdatePassword">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.personal-page {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.page-header {
  margin-bottom: 24px;
  width: 100%;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.user-form {
  max-width: 600px;
  width: 100%;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409EFF;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-input), :deep(.el-select), :deep(.el-date-picker) {
  width: 100%;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.phone-wrapper {
  display: flex;
  gap: 16px;
  align-items: center;
}

.phone-wrapper .el-input {
  flex: 1;
}

.password-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style> 
